﻿using System;
using System.Text;
using System.Drawing;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public static partial class NativeAOT
{
    [UnmanagedCallersOnly(EntryPoint = "fals")]
    public static unsafe int fals(double a, double b, double eps, IntPtr f_x_ptr, IntPtr x_ptr)
    {
        double* x = (double*)x_ptr.ToPointer();
        f_x = Marshal.GetDelegateForFunctionPointer<delegatefunc_x>(f_x_ptr);

        return fals(a, b, eps, x);
    }

    /// <summary>
    /// 方程求根试位法
    /// f(x)方程左端函数的函数名。
    /// </summary>
    /// <param name="a">a求根区间左端点。</param>
    /// <param name="b">b求根区间右端点。</param>
    /// <param name="eps">控制精度要求。</param>
    /// <param name="x">x存放方程根的初值。返回迭代终值。</param>
    /// <returns>函数返回迭代次数。若为-1则表示f(a)f(b)>0。</returns>
    public static unsafe int fals(double a, double b, double eps, double* x)
    {
        int m;
        double fa, fb, y;

        m = 0;
        fa = f_x(a);
        fb = f_x(b);
        if (fa * fb > 0) return (-1);
        do
        {
            m = m + 1;
            *x = (a * fb - b * fa) / (fb - fa);
            y = f_x(*x);
            if (y * fa < 0)
            {
                b = *x;
                fb = y;
            }
            else
            {
                a = *x;
                fa = y;
            }
        } while (Math.Abs(y) >= eps);
        return (m);
    }

    /*
        // 方程求根试位法例
        //主函数
        int main ()
        {
            int k;
            double x, func(double);
            //执行试位法
            k = fals(1.0, 3.0, 0.000001, func, &x);
            cout <<"迭代次数 = " <<k <<endl;
            cout <<"一个实根 x = " <<x <<endl;
            return 0;
        }
        // f(x)
        //计算方程左端函数f(x)值
        double func(double x)
        {
            double y;
            y = x*x*x - 2*x*x + x - 2;
            return y;
        }
    */
}

